package com.kgc.web.servlet; /**
 * <h3>项目名称:demo03050</h3>
 * <p>本API描述:${description}</p>
 * <p>@author : AliyZhang</p>
 * <p>@date : 2021-03-08 13:15</p>
 **/

import com.kgc.entity.FileDto;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "FileUpDownServlet", value = "/files.do")
public class FileUpDownServlet extends HttpServlet {
    /*
    处理文件列表浏览【list】上传[upload]下载[download]
     */
    @Override
    protected void service(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {

        String key = request.getParameter("key");
        switch (key){
            case "list":
                list(request,response);
                break;
            case "upload":

                break;
            case "download":
                download(request,response);
                break;
        }
    }

    private void list(HttpServletRequest request, HttpServletResponse response) {
        //获取下载文件的路径
        String downloadDir = request.getServletContext().getRealPath("static/download");
        File downloadDirFile = new File(downloadDir);
        File[] files = downloadDirFile.listFiles();
        List<FileDto> list=new ArrayList<>();
        for(File file:files){
            String name = file.getName();
            double size=file.length()/(1024*1.0);
            list.add(new FileDto(name, size));
        }
        request.setAttribute("list", list);
        try{
            request.getRequestDispatcher("jsp/file/listFiles.jsp").forward(request, response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void download(HttpServletRequest request, HttpServletResponse response) {
        String fileName = request.getParameter("fileName");
        String downloadPath = request.getServletContext().getRealPath("static/download/" + fileName);
        File downloadFile = new File(downloadPath);

        try{
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downloadFile));
            //以字节数组方式读取文件
            byte[] bs=new byte[1024];
            int len=-1;
            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
            response.setContentType("application/octet-stream");

            ServletOutputStream sos = response.getOutputStream();

            while((len=bis.read(bs))!=-1){
                sos.write(bs, 0, len);
            }
            sos.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
